package com.leo.dlq.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.consumer.rebalance.AllocateMessageQueueAveragely;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * 设置只重试一次, 且消费总是返回失败即可
 */
public class MyConsumer {
    public static void main(String[] args) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("consuer_grp_09_01");

        consumer.setNamesrvAddr("localhost:9876");

        // 设置负载均衡算法
        consumer.setAllocateMessageQueueStrategy(new AllocateMessageQueueAveragely());
        // 消费的模式：集群
        consumer.setMessageModel(MessageModel.CLUSTERING);
        // 消费的模式：广播
        //consumer.setMessageModel(MessageModel.BROADCASTING);

        // 设置消费者的线程数
        consumer.setConsumeThreadMin(1);
        consumer.setConsumeThreadMax(10);

        consumer.subscribe("tp_demo_09", "*");

        // 设置消息批处理的一个批次中消息的最大个数
        consumer.setConsumeMessageBatchMaxSize(1);


        // 只重试一次(默认16次), 消费不成功则进入死信队列 （广播模式无效, 有序消息会不断重试，间隔1秒，会阻塞后续消息的消费）
        consumer.setMaxReconsumeTimes(1);

        consumer.setMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {

                for (MessageExt msg : msgs) {
                    System.out.println(msg);
                }

                // 稍后消费(失败)
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                //return null;
            }
        });

        consumer.start();
    }
}